package com.nineclock.auth.intergration.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.intergration.entity.IntergrationAuthenticationEntity;
import com.nineclock.auth.intergration.processor.AuthenticationProcessor;
import com.nineclock.common.entity.Result;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 账号密码认证处理器
 * @author zhangyan
 * @date 2021/4/1 19:52
 */
@Component
public class UsernameAndPasswordAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    private SysUserFeign sysUserFeign;

    @Override
    public boolean support(IntergrationAuthenticationEntity entity) {

        //校验
        if (entity != null && StrUtil.isEmpty(entity.getAuthType())){
            //entity不为空,AuthType为空 --> 账号密码认证
            return true;
        }
        return false;
    }

    /**
     * 认证逻辑
     * @param entity
     * @return
     */
    @Override
    public SysUserDTO authenticate(IntergrationAuthenticationEntity entity) {

        //获取参数
        String username = entity.getAuthParameter("username");

        //判定
        if (StrUtil.isEmpty(username)){
            throw  new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //调用Feign 根据传递的手机号/用户名获取用户信息
        Result<SysUserDTO> result = sysUserFeign.query(username);
        SysUserDTO userDTO = result.getData();

        //组装返回
        return userDTO;
    }
}
